package main

import (
	"database/sql"
	"fmt"
	"os"
	"strconv"
	"strings"

	_ "github.com/go-sql-driver/mysql"
)

func main() {

	types := map[string]string{
		"BIGINT":  "int64",
		"VARCHAR": "string",
		"TINYINT": "bool",
		"DATE":    "*time.Time",
		"TEXT":    "string",
	}
	dsn := "golang:zxc,./123@tcp(43.139.115.142:3306)/user?charset=utf8mb4&loc=Local&parseTime=true"

	db, err := sql.Open("mysql", dsn)
	if err != nil {
		fmt.Println(err)
		return
	}

	if err = db.Ping(); err != nil {
		fmt.Println(err)
		return
	}
	sql := `
	show tables; 
	`
	rows, err := db.Query(sql)
	if err != nil {
		fmt.Println(err)
		return
	}

	for rows.Next() {
		var tableName string
		err = rows.Scan(&tableName)
		if err != nil {
			fmt.Println(err)
			break
		}

		sql = fmt.Sprintf("select * from %s", tableName)
		filedrows, err := db.Query(sql)
		if err != nil {
			fmt.Println(err)
			break
		}

		columns, err := filedrows.ColumnTypes()
		if err != nil {
			fmt.Println(err)
			break
		}
		fmt.Println(strings.Repeat("*", 40))
		fmt.Println(tableName)
		file, _ := os.Create(fmt.Sprintf("%s", tableName))
		fmt.Fprintf(file, "type %s struct{\n", tableName)
		for _, column := range columns {
			fmt.Println("\t", column.Name(), column.DatabaseTypeName())
			fmt.Fprintf(file, "\t%s\t%s\n", strings. (column.Name()), types[column.DatabaseTypeName()])
		}
		fmt.Fprintf(file, "}\n")

	}
	rows.Close()
}
